package org.jeecg.modules.solitaire_app.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.solitaire_app.app.entity.*;
import org.jeecg.modules.solitaire_app.app.entity.VO.ReceivingSealCarOrderVO;
import org.jeecg.modules.solitaire_app.app.entity.VO.SealCarOrderDetailVO;
import org.jeecg.modules.solitaire_app.app.entity.VO.YsySealCarOrderVO;
import org.jeecg.modules.solitaire_app.app.mapper.*;
import org.jeecg.modules.solitaire_app.app.query.AddSealCarOrderQuery;
import org.jeecg.modules.solitaire_app.app.query.ReceivingOrderListQuery;
import org.jeecg.modules.solitaire_app.app.query.SealCarOrderQuery;
import org.jeecg.modules.solitaire_app.app.query.UserSealCarOrderQuery;
import org.jeecg.modules.solitaire_app.app.service.IYsySealCarOrderService;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.system.service.ISysAnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 封车订单表
 * @Author: jeecg-boot
 * @Date: 2023-08-29
 * @Version: V1.0
 */
@Service
@Slf4j
@DS("ysy_db")
public class YsySealCarOrderServiceImpl extends ServiceImpl<YsySealCarOrderMapper, YsySealCarOrder> implements IYsySealCarOrderService {

    @Autowired
    private YsyUsersMapper ysyUsersMapper;
    @Autowired
    private YsyRefineryMapper refineryMapper;
    @Autowired
    private YsySystemConfigMapper ysySystemConfigMapper;
    @Autowired
    private YsyMealMapper ysyMealMapper;
    @Autowired
    private YsyOnsiteApplyMapper ysyOnsiteApplyMapper;
    @Autowired
    private YsySealCarOrderHisMapper ysySealCarOrderHisMapper;
    @Autowired
    private ISysAnnouncementService sysAnnouncementService;

    @Override
    @Transactional
    public Result<String> addSealCarOrder(AddSealCarOrderQuery addSealCarOrderQuery) {
        Result<String> result = new Result<>();
        try {

            YsyRefinery ysyRefinery = refineryMapper.selectOne(Wrappers.<YsyRefinery>lambdaQuery().eq(YsyRefinery::getRefineryId, addSealCarOrderQuery.getRefineryId()));
            if (ObjectUtil.isNull(ysyRefinery)) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("未找到该炼厂");
                return result;
            }

            YsySystemConfig ysySystemConfig = ysySystemConfigMapper.selectOne(Wrappers.<YsySystemConfig>lambdaQuery().eq(YsySystemConfig::getSource, 1));
            if (ObjectUtil.isNull(ysySystemConfig)) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("未找到配置信息");
                return result;
            }

            YsyUsers ysyUsers = ysyUsersMapper.selectOne(Wrappers.<YsyUsers>lambdaQuery().eq(YsyUsers::getId, addSealCarOrderQuery.getUserId()));
            if (ObjectUtil.isNull(ysyUsers)) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("未找到该用户");
                return result;
            }

            if (ysyUsers.getSealCarNum() == 0) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("封车服务次数不足");
                return result;
            }

            YsyMeal ysyMeal = ysyMealMapper.selectOne(Wrappers.<YsyMeal>lambdaQuery().eq(YsyMeal::getCountNum, 1).eq(YsyMeal::getType, 1));

            if (ObjectUtil.isNull(ysyMeal)) {
                //没有设置次数为1的套餐
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("未查询到封车次数信息");
                return result;
            }

            BigDecimal commissionPrice = new BigDecimal(0.00);

            if (ysySystemConfig.getType() == 1) {
                //比例
                commissionPrice = ysyMeal.getPrice().multiply(BigDecimal.valueOf(Long.parseLong(ysySystemConfig.getContent()))).divide(BigDecimal.valueOf(100));
            } else {
                //固定返佣金额
                commissionPrice = BigDecimal.valueOf(Long.valueOf(ysySystemConfig.getContent()));
            }

            //查询该炼厂是否有驻场人员
            List<YsyOnsiteApply> onsiteApplies = ysyOnsiteApplyMapper.selectList(Wrappers.<YsyOnsiteApply>lambdaQuery().like(YsyOnsiteApply::getRefineryIds, addSealCarOrderQuery.getRefineryId()).eq(YsyOnsiteApply::getStatus, 1));
            int sealUserFlag = onsiteApplies.size() > 0 ? 1 : 0;

            YsySealCarOrder ysySealCarOrder = YsySealCarOrder
                    .builder()
                    .carNum(addSealCarOrderQuery.getCarNum())
                    .additionalPrice(BigDecimal.ZERO)
                    .createTime(new Date())
                    .driverName(addSealCarOrderQuery.getDriverName())
                    .driverPhone(addSealCarOrderQuery.getDriverPhone())
                    .commission(commissionPrice).sealUserFlag(sealUserFlag)//该炼厂是否有驻场人员
                    .refineryAddress(ysyRefinery.getAddress())
                    .refineryId(ysyRefinery.getRefineryId() + "")
                    .refineryLat(ysyRefinery.getLat())
                    .refineryLng(ysyRefinery.getLng())
                    .refineryName(ysyRefinery.getRefineryName())
                    .userId(ysyUsers.getId())
                    .userName(ObjectUtil.isNull(ysyUsers.getRealName())
                            ? ysyUsers.getNickName()
                            : ysyUsers.getRealName())
                    .userPhone(ysyUsers.getPhone())
                    .refineryCity(ysyRefinery.getCity())
                    .orderType(sealUserFlag == 1 ? 1 : 2)
                    .build();

            this.baseMapper.insert(ysySealCarOrder);

            //减少用户的服务次数
            ysyUsers.setSealCarNum(ysyUsers.getSealCarNum() - 1);
            ysyUsersMapper.updateById(ysyUsers);

            //添加封车订单记录信息
            YsySealCarOrderHis ysySealCarOrderHis = new YsySealCarOrderHis();
            ysySealCarOrderHis.setSealCarOrder(ysySealCarOrder.getId());
            ysySealCarOrderHis.setType(0);
            ysySealCarOrderHis.setContentDesc("订单匹配中");
            ysySealCarOrderHis.setCreateTime(new Date());
            insertSealCarHisOrder(ysySealCarOrderHis);


//            //发公告通知处理
//            SysAnnouncement sysAnnouncement = new SysAnnouncement();
//            sysAnnouncement.setTitile("新封车订单通知");
//            sysAnnouncement.setMsgContent("有新封车订单，请尽快去处理！！！！");
//            sysAnnouncement.setCreateTime(new Date());
//            sysAnnouncement.setSendTime(new Date());
//            sysAnnouncement.setSendStatus("1");
//            sysAnnouncement.setMsgType("ALL");
//            sysAnnouncement.setMsgContent("1");
//            sysAnnouncement.setPriority("H");
//            sysAnnouncementService.save(sysAnnouncement);

            result.setMessage("订单创建成功");
            result.setCode(200);
            result.setSuccess(true);
            result.setResult(ysySealCarOrder.getId());
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setCode(500);
            result.setSuccess(false);
            result.setMessage("服务器响应失败");
            return result;
        }
    }

    @Override
    public Result<String> adminAdd(AddSealCarOrderQuery addSealCarOrderQuery) {
        Result<String> result = new Result<>();
        try {

            YsyRefinery ysyRefinery = refineryMapper.selectOne(Wrappers.<YsyRefinery>lambdaQuery().eq(YsyRefinery::getRefineryId, addSealCarOrderQuery.getRefineryId()));
            if (ObjectUtil.isNull(ysyRefinery)) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("未找到该炼厂");
                return result;
            }

            YsySystemConfig ysySystemConfig = ysySystemConfigMapper.selectOne(Wrappers.<YsySystemConfig>lambdaQuery().eq(YsySystemConfig::getSource, 1));
            if (ObjectUtil.isNull(ysySystemConfig)) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("未找到配置信息");
                return result;
            }

            YsyUsers ysyUsers = ysyUsersMapper.selectOne(Wrappers.<YsyUsers>lambdaQuery().eq(YsyUsers::getId, addSealCarOrderQuery.getUserId()));
            if (ObjectUtil.isNull(ysyUsers)) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("未找到该用户");
                return result;
            }

            if (ysyUsers.getSealCarNum() == 0) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("封车服务次数不足");
                return result;
            }

            YsyMeal ysyMeal = ysyMealMapper.selectOne(Wrappers.<YsyMeal>lambdaQuery().eq(YsyMeal::getCountNum, 1).eq(YsyMeal::getType, 1));

            if (ObjectUtil.isNull(ysyMeal)) {
                //没有设置次数为1的套餐
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("未查询到封车次数信息");
                return result;
            }

            BigDecimal commissionPrice = new BigDecimal(0.00);

            if (ysySystemConfig.getType() == 1) {
                //比例
                commissionPrice = ysyMeal.getPrice().multiply(BigDecimal.valueOf(Long.parseLong(ysySystemConfig.getContent()))).divide(BigDecimal.valueOf(100));
            } else {
                //固定返佣金额
                commissionPrice = BigDecimal.valueOf(Long.valueOf(ysySystemConfig.getContent()));
            }

            //查询该炼厂是否有驻场人员
            List<YsyOnsiteApply> onsiteApplies = ysyOnsiteApplyMapper.selectList(Wrappers.<YsyOnsiteApply>lambdaQuery().like(YsyOnsiteApply::getRefineryIds, addSealCarOrderQuery.getRefineryId()).eq(YsyOnsiteApply::getStatus, 1));
            int sealUserFlag = onsiteApplies.size() > 0 ? 1 : 0;

            YsySealCarOrder ysySealCarOrder = YsySealCarOrder
                    .builder()
                    .carNum(addSealCarOrderQuery.getCarNum())
                    .additionalPrice(BigDecimal.ZERO)
                    .createTime(new Date())
                    .driverName(addSealCarOrderQuery.getDriverName())
                    .driverPhone(addSealCarOrderQuery.getDriverPhone())
                    .commission(commissionPrice).sealUserFlag(sealUserFlag)//该炼厂是否有驻场人员
                    .refineryAddress(ysyRefinery.getAddress())
                    .refineryId(ysyRefinery.getRefineryId() + "")
                    .refineryLat(ysyRefinery.getLat())
                    .refineryLng(ysyRefinery.getLng())
                    .refineryName(ysyRefinery.getRefineryName())
                    .userId(ysyUsers.getId())
                    .userName(ObjectUtil.isNull(ysyUsers.getRealName())
                            ? ysyUsers.getNickName()
                            : ysyUsers.getRealName())
                    .userPhone(ysyUsers.getPhone())
                    .refineryCity(ysyRefinery.getCity())
                    .orderType(sealUserFlag == 1 ? 1 : 2)
                    .build();

            this.baseMapper.insert(ysySealCarOrder);

            //减少用户的服务次数
            ysyUsers.setSealCarNum(ysyUsers.getSealCarNum() - 1);
            ysyUsersMapper.updateById(ysyUsers);

            //添加封车订单记录信息
            YsySealCarOrderHis ysySealCarOrderHis = new YsySealCarOrderHis();
            ysySealCarOrderHis.setSealCarOrder(ysySealCarOrder.getId());
            ysySealCarOrderHis.setType(ysySealCarOrder.getStatus());
            ysySealCarOrderHis.setContentDesc("订单匹配中");
            ysySealCarOrderHis.setCreateTime(new Date());
            insertSealCarHisOrder(ysySealCarOrderHis);

            result.setMessage("订单创建成功");
            result.setCode(200);
            result.setSuccess(true);
            result.setResult(ysySealCarOrder.getId());
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setCode(500);
            result.setSuccess(false);
            result.setMessage("服务器响应失败");
            return result;
        }
    }

    @Override
    public Result<PageInfo<YsySealCarOrderVO>> getUserSealCarOrders(UserSealCarOrderQuery userSealCarOrderQuery) {
        Result<PageInfo<YsySealCarOrderVO>> result = new Result<>();
        try {
            PageHelper.startPage(userSealCarOrderQuery.getPageNo(), userSealCarOrderQuery.getPageSize());
            List<YsySealCarOrder> ysySealCarOrders = this.baseMapper.getUserSealCarOrders(userSealCarOrderQuery);
            PageInfo ysySealCarOrdersPageInfo = new PageInfo(ysySealCarOrders);
            List<YsySealCarOrderVO> ysySealCarOrderVOS = new ArrayList<>();
            ysySealCarOrdersPageInfo.getList().stream().forEach(item -> {
                YsySealCarOrderVO ysySealCarOrderVO = new YsySealCarOrderVO();
                BeanUtil.copyProperties(item, ysySealCarOrderVO);
                ysySealCarOrderVO.setOrderStatus(userSealCarOrderQuery.getStatus() == 1 ? "匹配中" : userSealCarOrderQuery.getStatus() == 2 ? "进行中" : "已完成");
                ysySealCarOrderVOS.add(ysySealCarOrderVO);
            });
            PageInfo pageInfo = new PageInfo(ysySealCarOrderVOS);
            pageInfo.setTotal(ysySealCarOrdersPageInfo.getTotal());
            result.setCode(200);
            result.setSuccess(true);
            result.setResult(pageInfo);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setCode(500);
            result.setSuccess(false);
            result.setMessage("服务器响应失败");
            return result;
        }
    }

    @Override
    public Result<SealCarOrderDetailVO> getUserSealCarOrderDetail(String orderId) {
        Result<SealCarOrderDetailVO> result = new Result<>();
        try {
            SealCarOrderDetailVO sealCarOrderDetailVO = new SealCarOrderDetailVO();

            YsySealCarOrder ysySealCarOrder = this.baseMapper.selectOne(Wrappers.<YsySealCarOrder>lambdaQuery()
                    .eq(YsySealCarOrder::getId, orderId));

            if (ObjectUtil.isNull(ysySealCarOrder)) {
                result.setCode(404);
                result.setSuccess(false);
                result.setMessage("找不到该订单");
                return result;
            }

            BeanUtil.copyProperties(ysySealCarOrder, sealCarOrderDetailVO);

            List<YsySealCarOrderHis> ysySealCarOrderHis = ysySealCarOrderHisMapper.selectList(Wrappers.<YsySealCarOrderHis>lambdaQuery()
                    .eq(YsySealCarOrderHis::getSealCarOrder, orderId).orderByDesc(YsySealCarOrderHis::getType));

            List<String> orderStatuss = new ArrayList<>();
            ysySealCarOrderHis.stream().forEach(item -> {
                orderStatuss.add(item.getType() + "");
            });

            if (orderStatuss.contains("12")) {
                sealCarOrderDetailVO.setOrderStatus(12 + "");
            } else if (orderStatuss.contains("10")) {
                sealCarOrderDetailVO.setOrderStatus(10 + "");
            } else {
                sealCarOrderDetailVO.setOrderStatus(ysySealCarOrderHis.get(0).getType() + "");
            }
            sealCarOrderDetailVO.setYsySealCarOrderHis(ysySealCarOrderHis);


            result.setSuccess(true);
            result.setCode(200);
            result.setResult(sealCarOrderDetailVO);
            return result;

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setCode(500);
            result.setSuccess(false);
            result.setMessage("服务器响应失败");
            return result;
        }
    }

    @Override
    public Result<PageInfo<YsySealCarOrderVO>> getSealCarOrderList(SealCarOrderQuery sealCarOrderQuery) {
        Result<PageInfo<YsySealCarOrderVO>> result = new Result<>();
        try {
            PageHelper.startPage(sealCarOrderQuery.getPageNo(), sealCarOrderQuery.getPageSize());
            List<YsySealCarOrder> ysySealCarOrders = new ArrayList<>();
            //派单任务
            if (sealCarOrderQuery.getType() == 1) {
                //查询用户所入驻炼厂
                String refineryIds = ysyOnsiteApplyMapper.selectOne(Wrappers.<YsyOnsiteApply>lambdaQuery()
                        .eq(YsyOnsiteApply::getUserId, sealCarOrderQuery.getUserId())).getRefineryIds();
                List<String> ids = Arrays.asList(refineryIds.split(","));
                ysySealCarOrders = this.baseMapper.selectList(Wrappers.<YsySealCarOrder>lambdaQuery()
                        //匹配中的数据
                        .eq(YsySealCarOrder::getStatus, 0)
                        //派单任务
                        .eq(YsySealCarOrder::getOrderType, 1)
                        //在对应炼厂内的数据
                        .in(YsySealCarOrder::getRefineryId, ids)
                        .orderByDesc(YsySealCarOrder::getCreateTime));
            } else if (sealCarOrderQuery.getType() == 2) {
                //抢单任务
                ysySealCarOrders = this.baseMapper.selectList(Wrappers.<YsySealCarOrder>lambdaQuery()
                        //匹配中的数据
                        .eq(YsySealCarOrder::getStatus, 0)
                        //抢单任务
                        .eq(YsySealCarOrder::getOrderType, 2)
                        .orderByDesc(YsySealCarOrder::getCreateTime));
            } else {
                //转单任务
                ysySealCarOrders = this.baseMapper.selectList(Wrappers.<YsySealCarOrder>lambdaQuery()
                        //已经转单的数据
                        .eq(YsySealCarOrder::getStatus, 11)
                        //转单人id
                        .eq(YsySealCarOrder::getTransferUserId, sealCarOrderQuery.getUserId())
                        //转单订单
                        .eq(YsySealCarOrder::getOrderType, 3)
                        //只查询转单待接单的
                        .eq(YsySealCarOrder::getTransferStatus, 0)
                        .orderByDesc(YsySealCarOrder::getCreateTime));
            }
            PageInfo pageInfo = new PageInfo(ysySealCarOrders);
            result.setResult(pageInfo);
            result.setCode(200);
            result.setSuccess(true);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setCode(500);
            result.setMessage("服务器响应失败");
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    @Transactional
    public synchronized Result<YsySealCarOrderVO> receivingOrder(String userId, String orderId) {
        Result<YsySealCarOrderVO> result = new Result<>();
        try {
            YsySealCarOrder ysySealCarOrder = this.baseMapper.selectOne(Wrappers.<YsySealCarOrder>lambdaQuery().eq(YsySealCarOrder::getId, orderId));
            if (ObjectUtil.isNull(ysySealCarOrder)) {
                result.setCode(200);
                result.setSuccess(false);
                result.setMessage("任务未找到");
                return result;
            }

            if (ysySealCarOrder.getStatus() != 0) {
                result.setCode(200);
                result.setSuccess(false);
                result.setMessage("订单被抢啦！！！");
                return result;
            }

            YsyUsers ysyUsers = ysyUsersMapper.selectOne(Wrappers.<YsyUsers>lambdaQuery().eq(YsyUsers::getId, userId));
            if (ObjectUtil.isNull(ysyUsers)) {
                result.setCode(200);
                result.setSuccess(false);
                result.setMessage("未找到该用户");
                return result;
            }

            YsyOnsiteApply ysyOnsiteApply = ysyOnsiteApplyMapper.selectOne(Wrappers.<YsyOnsiteApply>lambdaQuery()
                    .eq(YsyOnsiteApply::getUserId, userId));
            if (ObjectUtil.isNull(ysyOnsiteApply) || ysyOnsiteApply.getStatus() != 1) {
                result.setCode(200);
                result.setSuccess(false);
                result.setMessage("您尚未入驻该平台！！！");
                return result;
            }
            ysySealCarOrder.setStatus(1);
            ysySealCarOrder.setIncomingTime(new Date());
            ysySealCarOrder.setIncomingUserId(userId);
            ysySealCarOrder.setIncomingUserAvatar(ysyUsers.getAvatarUrl());
            String incomingUserName = "";
            if (ObjectUtil.isNotEmpty(ysyUsers.getRealName()) && ObjectUtil.isNotNull(ysyUsers.getRealName())) {
                incomingUserName = ysyUsers.getRealName();
            } else {
                incomingUserName = ysyUsers.getNickName();
            }
            ysySealCarOrder.setIncomingUserName(incomingUserName);
            ysySealCarOrder.setIncomingUserPhone(ysyUsers.getPhone());
            this.baseMapper.updateById(ysySealCarOrder);

            //添加封车订单记录信息
            YsySealCarOrderHis ysySealCarOrderHis = new YsySealCarOrderHis();
            ysySealCarOrderHis.setSealCarOrder(ysySealCarOrder.getId());
            ysySealCarOrderHis.setType(ysySealCarOrder.getStatus());
            ysySealCarOrderHis.setContentDesc(ysyOnsiteApply.getUserName() + "已接单");
            ysySealCarOrderHis.setCreateTime(new Date());
            insertSealCarHisOrder(ysySealCarOrderHis);

            YsySealCarOrderVO ysySealCarOrderVO = new YsySealCarOrderVO();
            BeanUtil.copyProperties(ysySealCarOrder, ysySealCarOrderVO);

            result.setCode(200);
            result.setSuccess(true);
            result.setMessage("接单成功");
            result.setResult(ysySealCarOrderVO);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setCode(500);
            result.setMessage("服务器响应失败");
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    @Transactional
    public Result<YsySealCarOrderVO> receivingOrderUpdate(String userId, String orderId, int type) {
        Result<YsySealCarOrderVO> result = new Result<>();
        try {
            YsySealCarOrder ysySealCarOrder = this.baseMapper.selectOne(Wrappers.<YsySealCarOrder>lambdaQuery().eq(YsySealCarOrder::getId, orderId));
            if (ObjectUtil.isNull(ysySealCarOrder)) {
                result.setCode(200);
                result.setSuccess(false);
                result.setMessage("未找到该订单");
                return result;
            }

            YsyUsers ysyUsers = ysyUsersMapper.selectOne(Wrappers.<YsyUsers>lambdaQuery().eq(YsyUsers::getId, userId));
            if (ObjectUtil.isNull(ysyUsers)) {
                result.setCode(200);
                result.setSuccess(false);
                result.setMessage("未找到该用户");
                return result;
            }
            YsyOnsiteApply ysyOnsiteApply = ysyOnsiteApplyMapper.selectOne(Wrappers.<YsyOnsiteApply>lambdaQuery()
                    .eq(YsyOnsiteApply::getUserId, userId));
            if (ObjectUtil.isNull(ysyOnsiteApply) || ysyOnsiteApply.getStatus() != 1) {
                result.setCode(200);
                result.setSuccess(false);
                result.setMessage("您尚未入驻该平台！！！");
                return result;
            }

            ysySealCarOrder.setStatus(type);
            ysySealCarOrder.setIncomingTime(new Date());
            ysySealCarOrder.setIncomingUserId(userId);
            ysySealCarOrder.setIncomingUserAvatar(ysyUsers.getAvatarUrl());
            String incomingUserName = "";
            if (ObjectUtil.isNotEmpty(ysyUsers.getRealName()) && ObjectUtil.isNotNull(ysyUsers.getRealName())) {
                incomingUserName = ysyUsers.getRealName();
            } else {
                incomingUserName = ysyUsers.getNickName();
            }
            ysySealCarOrder.setIncomingUserName(incomingUserName);
            ysySealCarOrder.setIncomingUserPhone(ysyUsers.getPhone());
            this.baseMapper.updateById(ysySealCarOrder);

            //添加封车订单记录信息
            YsySealCarOrderHis ysySealCarOrderHis = new YsySealCarOrderHis();
            ysySealCarOrderHis.setSealCarOrder(ysySealCarOrder.getId());
            ysySealCarOrderHis.setType(ysySealCarOrder.getStatus());
            ysySealCarOrderHis.setContentDesc(type == 2 ? ysyOnsiteApply.getUserName() + "正在赶往炼厂" :
                    type == 3 ? ysyOnsiteApply.getUserName() + "已到达炼厂" : "");
            ysySealCarOrderHis.setCreateTime(new Date());
            insertSealCarHisOrder(ysySealCarOrderHis);

            YsySealCarOrderVO ysySealCarOrderVO = new YsySealCarOrderVO();
            BeanUtil.copyProperties(ysySealCarOrder, ysySealCarOrderVO);

            result.setCode(200);
            result.setSuccess(true);
            result.setMessage("操作成功");
            result.setResult(ysySealCarOrderVO);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setCode(500);
            result.setMessage("服务器响应失败");
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    @Transactional
    public Result<YsySealCarOrderVO> transferOrder(String userId, String orderId, String transferUserId) {
        Result<YsySealCarOrderVO> result = new Result<>();
        try {
            YsySealCarOrder ysySealCarOrder = this.baseMapper.selectOne(Wrappers.<YsySealCarOrder>lambdaQuery().eq(YsySealCarOrder::getId, orderId));
            if (ObjectUtil.isNull(ysySealCarOrder)) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("未找到该订单");
                return result;
            }

            YsyUsers ysyUsers = ysyUsersMapper.selectOne(Wrappers.<YsyUsers>lambdaQuery().eq(YsyUsers::getId, userId));
            if (ObjectUtil.isNull(ysyUsers)) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("未找到该用户");
                return result;
            }
            YsyOnsiteApply ysyOnsiteApply = ysyOnsiteApplyMapper.selectOne(Wrappers.<YsyOnsiteApply>lambdaQuery()
                    .eq(YsyOnsiteApply::getUserId, userId));
            if (ObjectUtil.isNull(ysyOnsiteApply) || ysyOnsiteApply.getStatus() != 1) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("您尚未入驻该平台！！！");
                return result;
            }

            YsyUsers transferUser = ysyUsersMapper.selectOne(Wrappers.<YsyUsers>lambdaQuery()
                    .eq(YsyUsers::getId, transferUserId));
            if (ObjectUtil.isNull(transferUser)) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("未找到该用户");
                return result;
            }
            YsyOnsiteApply transferUserApply = ysyOnsiteApplyMapper.selectOne(Wrappers.<YsyOnsiteApply>lambdaQuery()
                    .eq(YsyOnsiteApply::getUserId, transferUserId));
            if (ObjectUtil.isNull(transferUserApply) || transferUserApply.getStatus() != 1) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("该用户未入驻平台！！！");
                return result;
            }

            if (transferUserId.equals(ysySealCarOrder.getTransferUserId())) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("订单不能转回！！！");
                return result;
            }

            if (transferUserId.equals(ysySealCarOrder.getIncomingUserId())) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("不能转单给自己！！！");
                return result;
            }

            ysySealCarOrder.setStatus(11);
            ysySealCarOrder.setTransferTime(new Date());
            ysySealCarOrder.setTransferStatus(0);
            ysySealCarOrder.setTransferUserId(transferUserId);
            ysySealCarOrder.setTransferUserName(transferUserApply.getUserName());
            ysySealCarOrder.setTransferUserPhone(transferUser.getPhone());
            ysySealCarOrder.setTransferUserAvatar(transferUser.getAvatarUrl());
            ysySealCarOrder.setOrderType(3);
            this.baseMapper.updateById(ysySealCarOrder);

            //添加封车订单记录信息
            YsySealCarOrderHis ysySealCarOrderHis = new YsySealCarOrderHis();
            ysySealCarOrderHis.setSealCarOrder(ysySealCarOrder.getId());
            ysySealCarOrderHis.setType(11);
            ysySealCarOrderHis.setContentDesc(ysyOnsiteApply.getUserName() + "已转单");
            ysySealCarOrderHis.setCreateTime(new Date());
            insertSealCarHisOrder(ysySealCarOrderHis);

            YsySealCarOrderVO ysySealCarOrderVO = new YsySealCarOrderVO();
            BeanUtil.copyProperties(ysySealCarOrder, ysySealCarOrderVO);

            result.setCode(200);
            result.setSuccess(true);
            result.setMessage("操作成功");
            result.setResult(ysySealCarOrderVO);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setCode(500);
            result.setMessage("服务器响应失败");
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    public Result<PageInfo<ReceivingSealCarOrderVO>> getUserReceivingOrderList(ReceivingOrderListQuery receivingOrderListQuery) {
        PageHelper.startPage(receivingOrderListQuery.getPageNo(), receivingOrderListQuery.getPageSize());
        Result<PageInfo<ReceivingSealCarOrderVO>> result = new Result<>();
        try {
            YsyUsers ysyUsers = ysyUsersMapper.selectOne(Wrappers.<YsyUsers>lambdaQuery()
                    .eq(YsyUsers::getId, receivingOrderListQuery.getUserId()));
            if (ObjectUtil.isNull(ysyUsers)) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("未找到该用户");
                return result;
            }
            YsyOnsiteApply ysyOnsiteApply = ysyOnsiteApplyMapper.selectOne(Wrappers.<YsyOnsiteApply>lambdaQuery()
                    .eq(YsyOnsiteApply::getUserId, receivingOrderListQuery.getUserId()));
            if (ObjectUtil.isNull(ysyOnsiteApply) || ysyOnsiteApply.getStatus() != 1) {
                result.setCode(500);
                result.setSuccess(false);
                result.setMessage("您尚未入驻该平台！！！");
                return result;
            }
            List<ReceivingSealCarOrderVO> receivingSealCarOrderVOS = new ArrayList<>();
            if (receivingOrderListQuery.getType() == 1) {
                //全部订单
                List<YsySealCarOrder> orderList = this.baseMapper.selectList(Wrappers.<YsySealCarOrder>lambdaQuery()
                        .eq(YsySealCarOrder::getTransferUserId, receivingOrderListQuery.getUserId())
                        .eq(YsySealCarOrder::getTransferStatus, 2)
                        .orderByDesc(YsySealCarOrder::getCreateTime)
                        .or()
                        .eq(YsySealCarOrder::getIncomingUserId, receivingOrderListQuery.getUserId())
                        .orderByDesc(YsySealCarOrder::getCreateTime));
                orderList.stream().forEach(item -> {
                    ReceivingSealCarOrderVO receivingSealCarOrderVO = new ReceivingSealCarOrderVO();
                    BeanUtil.copyProperties(item, receivingSealCarOrderVO);
                    receivingSealCarOrderVO.setCrossRegional(ysyOnsiteApply.getRefineryIds().
                            contains(item.getRefineryId()) ? 0 : 1);
                    receivingSealCarOrderVOS.add(receivingSealCarOrderVO);
                });
            } else if (receivingOrderListQuery.getType() == 2) {
                //已完成订单
                List<YsySealCarOrder> orderList = this.baseMapper.selectList(Wrappers.<YsySealCarOrder>lambdaQuery()
                        .eq(YsySealCarOrder::getTransferUserId, receivingOrderListQuery.getUserId())
                        .eq(YsySealCarOrder::getStatus, 12)
                        .eq(YsySealCarOrder::getTransferStatus, 2)
                        .orderByDesc(YsySealCarOrder::getCreateTime)
                        .or()
                        .eq(YsySealCarOrder::getStatus, 12)
                        .eq(YsySealCarOrder::getIncomingUserId, receivingOrderListQuery.getUserId())
                        .orderByDesc(YsySealCarOrder::getCreateTime));
                orderList.stream().forEach(item -> {
                    ReceivingSealCarOrderVO receivingSealCarOrderVO = new ReceivingSealCarOrderVO();
                    BeanUtil.copyProperties(item, receivingSealCarOrderVO);
                    receivingSealCarOrderVO.setCrossRegional(ysyOnsiteApply.getRefineryIds().
                            contains(item.getRefineryId()) ? 0 : 1);
                    receivingSealCarOrderVOS.add(receivingSealCarOrderVO);
                });
            } else if (receivingOrderListQuery.getType() == 3) {
                //我的转单
                List<YsySealCarOrder> orderList = this.baseMapper.selectList(Wrappers.<YsySealCarOrder>lambdaQuery()
                        .eq(YsySealCarOrder::getTransferUserId, receivingOrderListQuery.getUserId())
                        .eq(YsySealCarOrder::getStatus, 11)
                        .eq(YsySealCarOrder::getTransferStatus, 0)
                        .eq(YsySealCarOrder::getOrderType, 3)
                        .orderByDesc(YsySealCarOrder::getCreateTime));
                orderList.stream().forEach(item -> {
                    ReceivingSealCarOrderVO receivingSealCarOrderVO = new ReceivingSealCarOrderVO();
                    BeanUtil.copyProperties(item, receivingSealCarOrderVO);
                    receivingSealCarOrderVO.setCrossRegional(ysyOnsiteApply.getRefineryIds().
                            contains(item.getRefineryId()) ? 0 : 1);
                    receivingSealCarOrderVOS.add(receivingSealCarOrderVO);
                });
            } else if (receivingOrderListQuery.getType() == 4) {
                //进行中订单
                List<YsySealCarOrder> orderList = this.baseMapper.selectList(Wrappers.<YsySealCarOrder>lambdaQuery()
                        .eq(YsySealCarOrder::getTransferUserId, receivingOrderListQuery.getUserId())
                        .notIn(YsySealCarOrder::getStatus, Arrays.asList(0, 12, 11))
                        .orderByDesc(YsySealCarOrder::getCreateTime)
                        .or()
                        .eq(YsySealCarOrder::getIncomingUserId, receivingOrderListQuery.getUserId())
                        .notIn(YsySealCarOrder::getStatus, Arrays.asList(0, 12, 11))
                        .notIn(YsySealCarOrder::getOrderType, 3)
                        .orderByDesc(YsySealCarOrder::getCreateTime));
                orderList.stream().forEach(item -> {
                    ReceivingSealCarOrderVO receivingSealCarOrderVO = new ReceivingSealCarOrderVO();
                    BeanUtil.copyProperties(item, receivingSealCarOrderVO);
                    receivingSealCarOrderVO.setCrossRegional(ysyOnsiteApply.getRefineryIds().
                            contains(item.getRefineryId()) ? 0 : 1);
                    receivingSealCarOrderVOS.add(receivingSealCarOrderVO);
                });
            }

            PageInfo pageInfo = new PageInfo(receivingSealCarOrderVOS);
            result.setCode(200);
            result.setSuccess(true);
            result.setResult(pageInfo);
            return result;

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setCode(500);
            result.setMessage("服务器响应失败");
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    public Result<JSONArray> getOrderType(String userId) {
        Result<JSONArray> result = new Result<>();
        try {
//            //全部订单
//            int count = this.baseMapper.selectCount(Wrappers.<YsySealCarOrder>lambdaQuery()
//                    .eq(YsySealCarOrder::getTransferUserId, userId)
//                    .eq(YsySealCarOrder::getTransferStatus, 2)
//                    .or()
//                    .eq(YsySealCarOrder::getIncomingUserId, userId));
//
//            /*已完成订单*/
//            int count1 = this.baseMapper.selectCount(Wrappers.<YsySealCarOrder>lambdaQuery()
//                    .eq(YsySealCarOrder::getTransferUserId, userId)
//                    .eq(YsySealCarOrder::getStatus, 12)
//                    .eq(YsySealCarOrder::getTransferStatus, 2)
//                    .or()
//                    .eq(YsySealCarOrder::getStatus, 12)
//                    .eq(YsySealCarOrder::getIncomingUserId, userId));

            //我的转单
            int count2 = this.baseMapper.selectCount(Wrappers.<YsySealCarOrder>lambdaQuery()
                    .eq(YsySealCarOrder::getTransferUserId, userId)
                    .eq(YsySealCarOrder::getStatus, 11)
                    .eq(YsySealCarOrder::getTransferStatus, 0)
                    .eq(YsySealCarOrder::getOrderType, 3));

            //进行中订单
            int count3 = this.baseMapper.selectCount(Wrappers.<YsySealCarOrder>lambdaQuery()
                    .eq(YsySealCarOrder::getTransferUserId, userId)
                    .notIn(YsySealCarOrder::getStatus, Arrays.asList(0, 12, 11))
                    .or()
                    .eq(YsySealCarOrder::getIncomingUserId, userId)
                    .notIn(YsySealCarOrder::getStatus, Arrays.asList(0, 12, 11))
                    .notIn(YsySealCarOrder::getOrderType, 3));

            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "进行中的订单");
            jsonObject.put("num", count3);
            jsonObject.put("id", 4);

//            JSONObject jsonObject1 = new JSONObject();
//            jsonObject1.put("name", "我的转单");
//            jsonObject1.put("num", count2);
//            jsonObject1.put("id", 3);

            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("name", "已完成");
            jsonObject2.put("num", 0);
            jsonObject2.put("id", 2);

            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("name", "全部订单");
            jsonObject3.put("num", 0);
            jsonObject3.put("id", 1);
            jsonArray.add(jsonObject);
//            jsonArray.add(jsonObject1);
            jsonArray.add(jsonObject2);
            jsonArray.add(jsonObject3);
            result.setResult(jsonArray);
            result.setCode(200);
            result.setSuccess(true);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setCode(500);
            result.setMessage("服务器响应失败");
            result.setSuccess(false);
            return result;
        }
    }

    //新增封车订单记录
    public void insertSealCarHisOrder(YsySealCarOrderHis ysySealCarOrderHis) {
        ysySealCarOrderHisMapper.insert(ysySealCarOrderHis);
    }
}
